from django.core.exceptions import ObjectDoesNotExist

from django.db.models import Q
from django.utils import timezone
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.views import APIView
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from rest_framework_simplejwt.authentication import JWTAuthentication

from .models import Order, UserPackage
from .serializers import UserPackageListSerializer, UserPackageCreateSerializer, OrderSerializer, OrderCreateSerializer
from ..utils.pageNumberPagination import CustomPageNumberPagination
from ..utils.response_utils import api_response, ResponseCode


class ListOrderView(APIView):
    """
    获取订单列表接口
    支持根据订单编号、用户或邮箱、套餐、订单状态及创建时间范围查询
    """
    permission_classes = [AllowAny]
    authentication_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_description="获取订单列表",
        manual_parameters=[
            openapi.Parameter('order_no', openapi.IN_QUERY, description="订单编号查询（模糊匹配）",
                              type=openapi.TYPE_STRING),
            openapi.Parameter('user', openapi.IN_QUERY, description="用户名或邮箱查询（模糊匹配）",
                              type=openapi.TYPE_STRING),
            openapi.Parameter('package_id', openapi.IN_QUERY, description="套餐ID查询", type=openapi.TYPE_STRING),
            openapi.Parameter('status', openapi.IN_QUERY,
                              description="订单状态查询（待付款pending、已付款completed、已取消cancelled、已退款refunded）",
                              type=openapi.TYPE_STRING),
            openapi.Parameter('create_time_start', openapi.IN_QUERY,
                              description="创建时间开始（格式：YYYY-MM-DD HH:MM:SS）", type=openapi.TYPE_STRING),
            openapi.Parameter('create_time_end', openapi.IN_QUERY, description="创建时间结束（格式：YYYY-MM-DD HH:MM:SS）",
                              type=openapi.TYPE_STRING),
        ],
        responses={
            200: OrderSerializer(many=True),
            400: openapi.Response(description="无效的参数"),
        },
        tags=["订单管理"]
    )
    def get(self, request, *args, **kwargs):
        order_no = request.GET.get('order_no')
        user_query = request.GET.get('user')
        package_id = request.GET.get('package_id')
        status_param = request.GET.get('status')
        create_time_start = request.GET.get('create_time_start')
        create_time_end = request.GET.get('create_time_end')
        page = request.query_params.get("pageNo", 1)
        page_size = request.query_params.get("pageSize", 10)

        queryset = Order.objects.all().order_by('-create_time')

        if order_no:
            queryset = queryset.filter(order_no__icontains=order_no)
        if user_query:
            queryset = queryset.filter(Q(user__username__icontains=user_query) | Q(user__email__icontains=user_query))
        if package_id:
            queryset = queryset.filter(package_id=package_id)
        if status_param:
            queryset = queryset.filter(status=status_param)
        if create_time_start and create_time_end:
            queryset = queryset.filter(create_time__range=[create_time_start, create_time_end])
        elif create_time_start:
            queryset = queryset.filter(create_time__gte=create_time_start)
        elif create_time_end:
            queryset = queryset.filter(create_time__lte=create_time_end)

        paginator = CustomPageNumberPagination()
        paginator.page_size = int(page_size)
        paginator.page_query_param = 'pageNo'
        paginator.page_size_query_param = 'pageSize'
        result_page = paginator.paginate_queryset(queryset, request)
        serializer = OrderSerializer(result_page, many=True)
        paginated_response = paginator.get_paginated_response(serializer.data)

        return api_response(ResponseCode.SUCCESS, "获取订单列表成功", paginated_response.data)


class CreateOrderView(APIView):
    """
    创建订单接口
    """
    permission_classes = [AllowAny]
    authentication_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_description="创建订单",
        request_body=OrderCreateSerializer,
        responses={
            200: OrderSerializer,
            400: openapi.Response(description="参数错误"),
        },
        tags=["订单管理"]
    )
    def post(self, request, *args, **kwargs):
        serializer = OrderCreateSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return api_response(ResponseCode.SUCCESS, "订单创建成功", serializer.data)
        return api_response(ResponseCode.BAD_REQUEST, f"参数错误{serializer.errors}")


class UpdateOrderView(APIView):
    """
    更新订单接口
    """
    permission_classes = [AllowAny]
    authentication_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_description="更新订单",
        request_body=OrderCreateSerializer,
        responses={
            200: OrderSerializer,
            400: openapi.Response(description="参数错误或订单不存在"),
        },
        tags=["订单管理"]
    )
    def put(self, request, order_id, *args, **kwargs):
        try:
            order = Order.objects.get(pk=order_id)
        except ObjectDoesNotExist:
            return api_response(ResponseCode.BAD_REQUEST, "订单不存在")
        serializer = OrderCreateSerializer(order, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return api_response(ResponseCode.SUCCESS, "订单更新成功", serializer.data)
        return api_response(ResponseCode.BAD_REQUEST, f"参数错误{serializer.errors}")


class RetrieveOrderView(APIView):
    """
    获取订单详情接口
    """
    permission_classes = [AllowAny]
    authentication_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_description="获取订单详情",
        responses={
            200: OrderSerializer,
            400: openapi.Response(description="订单不存在"),
        },
        tags=["订单管理"]
    )
    def get(self, request, order_id, *args, **kwargs):
        try:
            order = Order.objects.get(pk=order_id)
        except ObjectDoesNotExist:
            return api_response(ResponseCode.BAD_REQUEST, "订单不存在")
        serializer = OrderSerializer(order)
        return api_response(ResponseCode.SUCCESS, "获取订单详情成功", serializer.data)


class DeleteOrderView(APIView):
    """
    批量删除订单接口
    """
    permission_classes = [AllowAny]
    authentication_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_description="批量删除订单",
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            properties={
                'ids': openapi.Schema(
                    type=openapi.TYPE_ARRAY,
                    items=openapi.Schema(type=openapi.TYPE_INTEGER),
                    description="待删除订单的ID数组"
                )
            },
            required=['ids']
        ),
        responses={
            200: openapi.Response(description="删除成功"),
            400: openapi.Response(description="参数错误"),
        },
        tags=["订单管理"]
    )
    def delete(self, request, *args, **kwargs):
        ids = request.data.get('ids')
        if not ids or not isinstance(ids, list):
            return api_response(ResponseCode.BAD_REQUEST, "ids参数错误")
        deleted_count, _ = Order.objects.filter(id__in=ids).delete()
        return api_response(ResponseCode.SUCCESS, f"成功删除{deleted_count}条订单数据")


class ListUserPackageView(APIView):
    """
    获取用户套餐列表接口
    """

    permission_classes = [AllowAny]
    authentication_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_description="获取用户套餐列表",
        manual_parameters=[
            openapi.Parameter('status', openapi.IN_QUERY, description="套餐状态（active/expired/disabled）",
                              type=openapi.TYPE_STRING),
            openapi.Parameter('keywords', openapi.IN_QUERY, description="用户名或套餐名称", type=openapi.TYPE_STRING),
        ],
        responses={
            200: openapi.Response(
                description="获取成功",
                schema=openapi.Schema(
                    type=openapi.TYPE_OBJECT,
                    properties={
                        'code': openapi.Schema(type=openapi.TYPE_INTEGER),
                        'msg': openapi.Schema(type=openapi.TYPE_STRING),
                        'data': openapi.Schema(
                            type=openapi.TYPE_ARRAY,
                            items=openapi.Schema(
                                type=openapi.TYPE_OBJECT,
                                properties={
                                    'username': openapi.Schema(type=openapi.TYPE_STRING),
                                    'email': openapi.Schema(type=openapi.TYPE_STRING),
                                    'status': openapi.Schema(type=openapi.TYPE_STRING),
                                    'package_name': openapi.Schema(type=openapi.TYPE_STRING),
                                    'expiration_time': openapi.Schema(type=openapi.TYPE_STRING),
                                }
                            )
                        )
                    }
                )
            ),
            400: openapi.Response(description="无效的参数"),
        },
        tags=["套餐管理"]
    )
    def get(self, request, *args, **kwargs):
        status_param = request.GET.get('status')
        keywords = request.GET.get('keywords')
        page = request.query_params.get("pageNo", 1)
        page_size = request.query_params.get("pageSize", 10)

        queryset = UserPackage.objects.all().select_related('user', 'package').order_by('-subscription_time')

        if status_param:
            queryset = queryset.filter(status=status_param)

        if keywords:
            queryset = queryset.filter(
                Q(user__username__icontains=keywords) | Q(package__name__icontains=keywords)
            )

        paginator = CustomPageNumberPagination()
        paginator.page_size = int(page_size)
        paginator.page_query_param = 'pageNo'
        paginator.page_size_query_param = 'page_size'
        result_page = paginator.paginate_queryset(queryset, request)
        serializer = UserPackageListSerializer(result_page, many=True)
        paginated_response = paginator.get_paginated_response(serializer.data)

        return api_response(ResponseCode.SUCCESS, "获取用户套餐列表成功", paginated_response.data)


class CreateUserPackageView(APIView):
    """
    创建用户套餐接口
    """

    permission_classes = [AllowAny]
    authentication_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_description="创建用户套餐",
        request_body=UserPackageCreateSerializer,
        responses={
            200: openapi.Response(description="创建成功"),
            400: openapi.Response(description="无效的参数"),
        },
        tags=["套餐管理"]
    )
    def post(self, request, *args, **kwargs):
        serializer = UserPackageCreateSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return api_response(ResponseCode.SUCCESS, "用户套餐创建成功")
        return api_response(ResponseCode.BAD_REQUEST, f"参数错误{serializer.errors}")


class UpdateUserPackageView(APIView):
    """
    更新用户套餐接口
    """

    permission_classes = [AllowAny]
    authentication_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_description="更新用户套餐",
        request_body=UserPackageCreateSerializer,
        responses={
            200: openapi.Response(description="更新成功"),
            400: openapi.Response(description="无效的参数"),
        },
        tags=["套餐管理"]
    )
    def put(self, request, user_package_id, *args, **kwargs):
        try:
            package = UserPackage.objects.get(id=user_package_id)
        except ObjectDoesNotExist:
            return api_response(ResponseCode.NOT_FOUND, "用户套餐未找到")

        serializer = UserPackageCreateSerializer(package, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return api_response(ResponseCode.SUCCESS, "用户套餐更新成功")
        return api_response(ResponseCode.BAD_REQUEST, f"参数错误{serializer.errors}")


class DeleteUserPackageView(APIView):
    """
    批量删除用户套餐接口
    """

    permission_classes = [AllowAny]
    authentication_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_description="批量删除用户套餐",
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            properties={
                'ids': openapi.Schema(type=openapi.TYPE_ARRAY, items=openapi.Schema(type=openapi.TYPE_STRING)),
            },
        ),
        responses={
            200: openapi.Response(description="删除成功"),
            400: openapi.Response(description="无效的参数"),
        },
        tags=["套餐管理"]
    )
    def delete(self, request, *args, **kwargs):
        ids = request.data.get('ids', [])
        if not ids:
            return api_response(ResponseCode.BAD_REQUEST, "未提供有效的ID列表")

        user_packages = UserPackage.objects.filter(id__in=ids)
        if not user_packages.exists():
            return api_response(ResponseCode.NOT_FOUND, "未找到对应的用户套餐")

        user_packages.delete()
        return api_response(ResponseCode.SUCCESS, "用户套餐删除成功")
